package cn.wolfcode.mq;

import cn.wolfcode.ws.WebSocketServer;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@RocketMQMessageListener(
        consumerGroup = "MQOrderResultListener",
        topic = MQConstant.ORDER_RESULT_TOPIC
)
@Slf4j
public class MQOrderResultListener implements RocketMQListener<OrderMQResult> {
    @Override
    public void onMessage(OrderMQResult orderMQResult) {
        log.info("进入到通知对列中");
        try {
            // 可能消费太快
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        // 如何把数据推给客户端 ?
        // 现在OrderResult 成功时候      seckillId  time  token  orderNo
        //                 失败的情况    seckillId  time  token  code  msg
        // 我现在想直接把orderResult对象直接推给客户端
        // 根据token获取客户端的信息再去推数据
        String token = orderMQResult.getToken();
        WebSocketServer webSocketServer = WebSocketServer.clients.get(token);
        if (webSocketServer != null) {
            try {
                // 推送信息   成功才有订单编号
                webSocketServer.getSession().getBasicRemote().sendText(JSON.toJSONString(orderMQResult));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}